import tempfile
import subprocess
import sys

def run_python(code: str, timeout: float | None = None):
    lines = code.splitlines()
    tail = lines[-1:]
    if tail and '=' not in tail[0]:
        code = '\n'.join(lines[:-1]) + '\nprint(' + tail[0] + ')'
    with tempfile.NamedTemporaryFile('w', suffix='.sh') as f:
        f.write(code)
        f.flush()
        shell = [sys.executable, '--', f.name]
        with subprocess.Popen(shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
            result = b''
            accum = b''
            while p.poll() is None:
                try:
                    stdout, stderr = p.communicate(b'y\n', timeout=timeout)
                    assert stderr is None
                except subprocess.TimeoutExpired:
                    p.kill()
                    result += b'\n[Timeout expired]'
                    break
                else:
                    accum += stdout
                    try:
                        sys.stdout.write(accum.decode())
                        accum = b''
                        sys.stdout.flush()
                    except UnicodeDecodeError:
                        pass
                    result += stdout
            try:
                result = result.decode()
            except UnicodeDecodeError:
                try:
                    result = result.decode('latin1')
                except UnicodeDecodeError:
                    result = ''
            try:
                p.wait(timeout=2)
            except subprocess.TimeoutExpired:
                pass
            result = {'output': result, 'exit_code': p.returncode}
    return result
